package com.holystone.splunk.utils;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.util.*;

/**
 * @author huyan
 * @date 2017/9/14
 * @desc: JSON 转换工具类
 */
public class JSONUtils {

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 将json字符串转换为map集合
     *
     * @param jsonStr
     * @return
     * @throws IOException
     */
    public static Map<String, String> jsonStr2Map(String jsonStr) throws IOException {
        return mapper.readValue(jsonStr, Map.class);
    }

    /**
     * 将json字符串数组转换为list集合
     * @param jsonList
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> List<T> jsonStr2List(String jsonList, Class<?> clazz) throws IOException {
        JavaType javaType = getCollectionType(ArrayList.class, clazz);
        return mapper.readValue(jsonList, javaType);
    }

    /**
     * 将json字符转成set集合
     * @param jsonSet
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> Set<T> jsonStr2Set(String jsonSet, Class<?> clazz) throws IOException {
        JavaType javaType = getCollectionType(HashSet.class, clazz);
        return mapper.readValue(jsonSet, javaType);
    }

    /**
     * 将json字符串对象转换成java对象
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T jsonStr2JavaBean(String jsonStr, Class<T> clazz) throws IOException {
        return mapper.readValue(jsonStr, clazz);
    }

    /**
     * 将java对象转成json字符串
     *
     * @param object
     * @return
     * @throws IOException
     */
    public static String javaBean2Json(Object object) throws IOException {
        return mapper.writeValueAsString(object);
    }

    /**
     * 将json字符串转成json对象
     * @param jsonStr
     * @return
     * @throws IOException
     */
    public static JsonNode jsonStr2JsonNode(String jsonStr) throws IOException {
        return mapper.readTree(jsonStr);
    }

    /**
     * 获取集合的泛型的javaType
     * @param collectionClass 集合的类型
     * @param elementClass 泛型的类型
     * @return
     */
    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClass) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClass);
    }


}
